/**
 * create by young (young2f@outlook.com) on 2020/12/3
 */
'use strict';
const base = require('../base/controllerBase');
const _stringUtils = require('../utils/stringUtils');
const _fileUtils = require('../utils/fileUtils');
const moment = require('moment');
const _ = require('lodash');
const fs = require('fs');

class GlobalController extends base {
  /**
   * 旧数据整理
   * @returns {Promise<void>}
   */
  async dataEdit() {
    const { ctx } = this;
    try {
      let count = 0;
      const list = await ctx.app.dbs.find('Material', {});
      _.map(list, async item => {
        const { code } = item;
        const res = await ctx.app.dbs.updateOne('Material', { code }, { storeCount: 0 });
        count += 1;
      });
      // const list = await ctx.app.dbs.find('SalesOrder', {});

//       _.map(list, async item => {
//         const { code } = item;
//         let outboundAmount = 0;
//         const arr = await ctx.app.dbs.find('OutboundLot', { orderCode: code });
//         _.map(arr, async it => {
//           const { outboundCount = 0, price = 0 } = it;
//           outboundAmount += outboundCount * price;
//         });
// console.log('cccc',code,outboundAmount);
//         const res = await ctx.app.dbs.updateOne('SalesOrder', { code }, { outboundAmount });
//         count++
//       });
      ctx.body = { status: 'ok', result: count };
      ctx.status = 200;
    } catch (e) {
      console.error(e);
      const _message = e && e.message ? e.message : this.ERROR_MSG;
      ctx.body = { status: 'error', message: _message, result: e };
      ctx.status = 200;
    }
  }

  async cities() {
    const { ctx } = this;
    try {
      const path = ctx.app.config.infoPath + '/cities.json';
      console.log('行政区域', path);
      const file = require(path);
      ctx.body = { status: 'ok', result: file };
      ctx.status = 200;
    } catch (e) {
      console.error(e);
      const _message = e && e.message ? e.message : this.ERROR_MSG;
      ctx.body = { status: 'error', message: _message, result: e };
      ctx.status = 200;
    }
  }


  async getCode() {
    const { ctx, service } = this;
    try {
      const { body } = ctx.request;
      const model = {
        prefix: { type: 'string' },
      };

      ctx.validate(model, body);
      const { prefix } = body;
      const code = _stringUtils.getCode(prefix);
      console.log('codeee', code);
      ctx.body = { status: 'ok', result: { code } };
      ctx.status = 200;
    } catch (e) {
      const _message = e && e.message ? e.message : this.ERROR_MSG;
      ctx.body = { status: 'error', message: _message, result: e };
      ctx.status = 200;
    }
  }

  async getModel() {
    const { ctx, service } = this;
    try {
      const { body } = ctx.request;
      const model = {
        tenantCode: { type: 'string' },
        table: { type: 'string' },
      };
      console.log('getModel', body);
      ctx.validate(model, body);
      const result = await service.globalService.getModel(body);

      ctx.body = { status: 'ok', result };
      ctx.status = 200;
    } catch (e) {
      const _message = e && e.message ? e.message : this.ERROR_MSG;
      console.error('get modal error', e.message);
      ctx.body = { status: 'error', message: _message, result: e };
      ctx.status = 200;
    }
  }

  async clearTestData() {
    const { ctx } = this;
    try {
      const { body } = ctx.request;
      const model = {
        tenantCode: { type: 'string' },
      };
      console.log('clearTestData', body);
      ctx.validate(model, body);

      const { tenantCode } = body;
      //清除采购单
      const res = await ctx.app.dbs.updateMany('ProcureOrder', { tenantCode },{isDeleted:true});
      const res1 = await ctx.app.dbs.updateMany('ProcureMaterialRecord', { tenantCode },{isDeleted:true});
      const res2 = await ctx.app.dbs.updateMany('InboundLot', { tenantCode },{isDeleted:true});
      //清除订单
      const res3 = await ctx.app.dbs.updateMany('SalesOrder', { tenantCode },{isDeleted:true});
      const res4 = await ctx.app.dbs.updateMany('SalesProdRecord', { tenantCode },{isDeleted:true});
      const res5 = await ctx.app.dbs.updateMany('OutboundLot', { tenantCode },{isDeleted:true});
      const res8 = await ctx.app.dbs.updateMany('SalesReturnGoodsOrder', { tenantCode },{isDeleted:true});
      //更新所有库存为0
      const res6=await ctx.app.dbs.updateMany('Material', { tenantCode },{procureCount:0,storeCount:0,});
      const res7 = await ctx.app.dbs.updateMany('Discard', { tenantCode },);
      ctx.body = { status: 'ok', result: {} };
      ctx.status = 200;
    } catch (e) {
      console.error(e);
      const _message = e && e.message ? e.message : this.ERROR_MSG;
      ctx.body = { status: 'error', message: _message, result: e };
      ctx.status = 200;
    }
  }

  async createPic() {
    const { ctx, service } = this;
    try {
      const { body } = ctx.request;
      const model = {
        tenantCode: { type: 'string' },
        table: { type: 'string' },
      };
      console.log('createPic', body);
      ctx.validate(model, body);
      const result = await ctx.app.dbs.insert('Pic', body);
      ctx.body = { status: 'ok', result };
      ctx.status = 200;
    } catch (e) {
      const _message = e && e.message ? e.message : this.ERROR_MSG;
      console.error('createPic error', e.message);
      ctx.body = { status: 'error', message: _message, result: e };
      ctx.status = 200;
    }
  }

  async findPicMany() {
    const { ctx, service } = this;
    try {
      const { body } = ctx.request;
      const model = {
        tenantCode: { type: 'string' },
        table: { type: 'string' },
      };
      console.log('findPicMany', body);
      ctx.validate(model, body);
      const result = await ctx.app.dbs.find('Pic', body);
      console.log('findPicMany result', result);
      ctx.body = { status: 'ok', result };
      ctx.status = 200;
    } catch (e) {
      const _message = e && e.message ? e.message : this.ERROR_MSG;
      console.error('get modal error', e.message);
      ctx.body = { status: 'error', message: _message, result: e };
      ctx.status = 200;
    }
  }

  async deletePic() {
    const { ctx, service } = this;
    try {
      const { body } = ctx.request;
      const model = {
        tenantCode: { type: 'string' },
        table: { type: 'string' },
      };
      console.log('deletePic', body);
      ctx.validate(model, body);
      const result = await ctx.app.dbs.deleteMany('Pic', body);
      ctx.body = { status: 'ok', result };
      ctx.status = 200;
    } catch (e) {
      const _message = e && e.message ? e.message : this.ERROR_MSG;
      console.error('get modal error', e.message);
      ctx.body = { status: 'error', message: _message, result: e };
      ctx.status = 200;
    }
  }

  async download() {
    const { ctx } = this;

    const query = this.ctx.query;
    const { file } = query;
    console.log('download', file);
    // ctx.attachment([filename], [options]) 将 Content-Disposition 设置为 “附件” 以指示客户端提示下载。
    console.log('fileee', getFileName(file));

    ctx.attachment(getFileName(file), {
      fallback: true,
      type: 'attachment' // [string] attachment/inline
    });
    const fileSize = fs.statSync(file).size;
    ctx.set('Content-Length', fileSize);
    ctx.set('Content-Disposition', `attachment; filename=${getFileName(file)}`);
    ctx.body = fs.createReadStream(file);
  }

  async upload() {
    const { ctx, service } = this;
    const query = this.ctx.query;
    const body = { query, files: ctx.request.files };
    const result = await service.globalService.uploadPDF(body);

    ctx.body = result;
    ctx.status = 200;
  }

  async uploadFile() {
    const { ctx, service } = this;
    try {
      console.log('upload file', ctx.query);
      console.log('upload file', ctx.request);

      ctx.body = { status: 'ok' };
      ctx.status = 200;
    } catch (e) {
      const _message = e && e.message ? e.message : this.ERROR_MSG;
      console.error('get modal error', e.message);
      ctx.body = { status: 'error', message: _message, result: e };
      ctx.status = 200;
    }
  }
}

module.exports = GlobalController;

function getFileName(path) {
  var match = path.match(/\\([^\\]+)$/); // 使用正则表达式匹配反斜杠后的部分
  return match ? match[1] : path; // 如果匹配成功则返回匹配的部分作为文件名，否则返回原字符串
}
